package com.sa35.fbs.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Table;
import org.hibernate.persister.entity.AbstractEntityPersister;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.LocalSessionFactoryBean;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.sa35.fbs.dao.GenericDao;

/**
 * This class defines most of the basics Hibernate operations that uses Spring's
 * {@link HibernateTemplate}, with the addition of Java 5 generics type.
 * 
 * @author Daniel Baktiar
 * 
 * @param <T>
 *            type of the persistence domain model
 * @param <ID>
 *            type of the surrogate key of the domain models (normally this will
 *            be set to {@link Long}
 */
public abstract class GenericHibernateDao<T, ID extends Serializable> extends
		HibernateDaoSupport implements GenericDao<T, ID> {

	private final Class<T> domainClass;

	/**
	 * SLF4J logger. Hides the one from superclass as this one is better.
	 */
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * constructor, initiate the domain class name.
	 */
	public GenericHibernateDao() {
		this.domainClass = resolveDomainClass(this.getClass());
	}

	@SuppressWarnings("unchecked")
	private Class<T> resolveDomainClass(Class<?> clazz) {
		Type type = clazz.getGenericSuperclass();
		return (type instanceof ParameterizedType) ? (Class<T>) ((ParameterizedType) type)
				.getActualTypeArguments()[0] : resolveDomainClass(clazz
				.getSuperclass());
	}

	/**
	 * get the type of persistence domain class.
	 */
	public Class<T> getDomainClass() {
		return domainClass;
	}

	public T loadById(ID id) {
		return getHibernateTemplate().load(getDomainClass(), id);
	}

	/**
	 * Find a persistence model by its surrogate key (id). If the row with the
	 * specified id does not exist in the database, the returned object will be
	 * null.
	 */
	public T findById(ID id) {
		final T domain;
		if (id == null) {
			return null;
		}
		domain = getHibernateTemplate().get(getDomainClass(), id);
		return domain;
	}

	/**
	 * find all persistence models of given type.
	 */
	@SuppressWarnings("unchecked")
	public List<T> findAll() {
		return getHibernateTemplate().findByCriteria(
				DetachedCriteria.forClass(getDomainClass()));
	}

	/**
	 * find persistence models by example.
	 */
	// @SuppressWarnings("unchecked")
	// public List<T> findByExample(T exampleInstance, String...
	// excludeProperty) {
	// Example example = Example.create(exampleInstance);
	// if(excludeProperty != null) {
	// for(String exclude: excludeProperty) {
	// example.excludeProperty(exclude);
	// }
	// }
	// return getHibernateTemplate().findByCriteria(
	// DetachedCriteria.forClass(getDomainClass())
	// .add(example)
	// );
	// }

	/**
	 * delete a persistence model.
	 */
	public void delete(T domain) {
		getHibernateTemplate().delete(domain);
	}

	public void delete(Collection<? extends T> domains) {
		getHibernateTemplate().deleteAll(domains);
	}

	/**
	 * save a single model (either create a new persistence model or updating an
	 * existing one).
	 */
	public void save(T domain) {
		getHibernateTemplate().saveOrUpdate(domain);
	}

	/**
	 * count the number of rows which has the models.
	 */
	public long count() {
		return (Long) getHibernateTemplate().find(
				"select count(*) from " + domainClass.getName() + " a").get(0);
	}

	/**
	 * save a list of Hibernate domain models in one go.
	 */
	public void save(Collection<? extends T> domains) {
		getHibernateTemplate().saveOrUpdateAll(domains);
	}

	/**
	 * flush the associated Hibernate session.
	 */
	public void flush() {
		getHibernateTemplate().flush();
	}

	/**
	 * clear the associated Hibernate session.
	 */
	public void clear() {
		getHibernateTemplate().clear();
	}

	@SuppressWarnings("unchecked")
	protected List<T> findByCriteria(Criterion... criterions) {
		DetachedCriteria detachedCriteria = DetachedCriteria
				.forClass(getDomainClass());
		for (Criterion criterion : criterions) {
			detachedCriteria.add(criterion);
		}

		return getHibernateTemplate().findByCriteria(detachedCriteria);
	}

	// @SuppressWarnings({ "unchecked", "rawtypes" })
	// protected CorePaginatedList constructPaginatedResult(
	// PaginatedRequest pgReq,
	// DetachedCriteria countCriteria,
	// DetachedCriteria listCriteria) {
	// // the the total number of rows first, and construct the result object
	// HibernateTemplate ht = getHibernateTemplate();
	// int noOfRows = DaoUtil.extractCount(ht.findByCriteria(countCriteria));
	//
	// // get the list of models
	// int rowStart = pgReq.getRowStart();
	// int pageSize = pgReq.getPageSize();
	// List queryResult = ht.findByCriteria(listCriteria, rowStart, pageSize);
	//
	// return new CorePaginatedListImpl(pgReq.getPageNum(), pageSize, noOfRows,
	// queryResult);
	// }

//	protected LocalSessionFactoryBean lsfb;
//
//	@Autowired
//	public void setLsfb(LocalSessionFactoryBean lsfb) {
//		this.lsfb = lsfb;
//	}
//
//	protected Configuration getConfiguration() {
//		return lsfb.getConfiguration();
//	}
//
//	/**
//	 * Only works if the column name is mapped to a <b>SINGLE</b> property.
//	 * Update tcm_daos.xml as necessary.
//	 */
//	// @author Johan
//	public Integer getColumnLength(String propertyName) {
//		if (propertyName == null)
//			throw new IllegalArgumentException("property name must not be null");
//		AbstractEntityPersister persister = (AbstractEntityPersister) getHibernateTemplate()
//				.getSessionFactory().getClassMetadata(getDomainClass());
//		Table t = getConfiguration()
//				.getClassMapping(getDomainClass().getName()).getTable();
//		String[] colNames = (persister.getPropertyColumnNames(propertyName));
//		return (t.getColumn(new Column(colNames[0])).getLength());
//	}

	public List<?> executeCriteria(DetachedCriteria criteria) {
		return getHibernateTemplate().findByCriteria(criteria);
	}

	@Autowired
	public void setSessionFactoryOverride(SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

}
